package com.tro.common.util.office;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFTextParagraph;
import org.apache.poi.xslf.usermodel.XSLFTextRun;
import org.apache.poi.xslf.usermodel.XSLFTextShape;

import com.tro.common.util.string.StringUtlis;

public class pptXToHtml {
	public static String pptxToHtml(String fileName, String path, String imgPath) {
		String htmlStr="转换异常";
		try {
			FileInputStream is = new FileInputStream(path+fileName);
			XMLSlideShow ppt = new XMLSlideShow(is);
			is.close();
			
			Dimension pgsize = ppt.getPageSize();
			System.out.println(pgsize.width + "--" + pgsize.height);

			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < ppt.getSlides().size(); i++) {
				try {
					for (XSLFShape shape : ppt.getSlides().get(i).getShapes()) {
						if (shape instanceof XSLFTextShape) {
							XSLFTextShape tsh = (XSLFTextShape) shape;
							for (XSLFTextParagraph p : tsh) {
								for (XSLFTextRun r : p) {
									r.setFontFamily("宋体");
								}
							}
						}
					}
					BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
					Graphics2D graphics = img.createGraphics();
					// clear the drawing area
					graphics.setPaint(Color.white);
					graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
					ppt.getSlides().get(i).draw(graphics);
					String imagePath = imgPath + StringUtlis.getGUID() + "-" + (i + 1) + ".png";
					sb.append("<br>");
					sb.append("<img src=" + "\"" + imagePath + "\"" + "/>");
					FileOutputStream out = new FileOutputStream(imagePath);
					javax.imageio.ImageIO.write(img, "png", out);
					out.close();
				} catch (Exception e) {
					//转换异常，打印都不想打印
				}
			}
			System.out.println("success");
			htmlStr = sb.toString();
			
		} catch (Exception e) {
		}
		return htmlStr;
	}

	public static void main(String[] args) throws IOException {
		String content=pptxToHtml("spring mvc 配置多视图解析.pptx", "/Users/apple/Desktop/", "/Users/apple/Desktop/image/");
		FileUtils.writeStringToFile(new File("/Users/apple/Desktop/", "人员选择系分1.html"), content, "utf-8");
	}
}
